//
//  XMLHomeViewModel.swift
//  Weibo
//
//  Created by mac on 16/5/14.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

class XMLHomeViewModel: NSObject {
    
    var homeArray :[XMLHomeCellViewModel]?

    func requestData(isPullUp :Bool,complete :((isSuccess :Bool,message :String)->())) {
        
        var maxID :Int64 = 0
        var sinceID :Int64 = 0
        if isPullUp {
        
            maxID = self.homeArray?.last?.home?.id ?? 0
            if maxID > 0 {
            
                maxID -= 1
            }
        }else {
        
            sinceID = self.homeArray?.first?.home?.id ?? 0
        }
        
        XMLNetWorkTools.sharedTools.requestHomeData((XMLUserAcountViewModel.sharedUserAcountViewModel.userAcount?.access_token)!,maxID: maxID,sinceID: sinceID) { (response, error) -> () in
            
            var message = "没有加载到网络数据"
            if error != nil {
                
                print("网络请求异常")
                complete(isSuccess: false,message: message)
            }
            //            print(response)
            guard let dict = response as? [String :AnyObject] else {
                
                print("不是字典类型")
                complete(isSuccess: false,message: message)
                return
            }
            
            guard let dictArray = dict["statuses"] as? [[String :AnyObject]] else {
                
                return
            }
            var nmArray = [XMLHomeCellViewModel]()
            for dict in dictArray {
                let home = XMLHome(dict: dict)
                let homeViewCellModel = XMLHomeCellViewModel(home :home)
                nmArray.append(homeViewCellModel)
            }
            if self.homeArray == nil {
            
                self.homeArray = [XMLHomeCellViewModel]()
            }
            
            if isPullUp {
            
                self.homeArray! += nmArray
            }else {
            
                
                self.homeArray = nmArray + self.homeArray!
            }
            let count = nmArray.count
            if count > 0 {
                message = "加载了\(count)条微博数据"
            }
            
            complete(isSuccess: true,message:message )
//            self.tableView.reloadData()
        }
    }
    
}
